/**
 * @Title: CorsConfig.java
 * @Package com.kaver.sso.web.config
 * @author roc
 * @date Aug 11, 2021 10:04:03 AM
 * @version V1.0
 * @copyright kaver
 */
package com.kaver.sso.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @ClassName: CorsConfig
 * @Description: 跨域配置
 * @author roc
 * @date Aug 11, 2021 10:04:03 AM
 * 
 */
@Configuration
public class CorsConfig {
    
    @Value("${cors.allowOrigin.url:/**}")
    private String corsAllowOriginUrl;

    @ConditionalOnProperty(name = "cors.allowOrigin.enable", havingValue = "true", matchIfMissing = false)
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration(corsAllowOriginUrl, corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
